import 'package:flutter/cupertino.dart';

class MyImage extends StatefulWidget {
  const MyImage({required this.imageProvider});

  final ImageProvider imageProvider;

  @override
  State<MyImage> createState() => _MyImageState();
}

class _MyImageState extends State<MyImage> {
  ImageStream? _imageStream;
  ImageInfo? _imageInfo;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    //我们在这里调用_getImage是因为createLocalImageConfiguration()需要
    //如果依赖项发生更改，在更改相关的情况下再次调用
    //到该方法使用的DefaultAssetBundle、MediaQuery等。
    _getImage();
  }

  @override
  void didUpdateWidget(MyImage oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.imageProvider != oldWidget.imageProvider) {
      _getImage();
    }
  }

  void _getImage() {
    final ImageStream? oldImageStream = _imageStream;
    _imageStream = widget.imageProvider.resolve(createLocalImageConfiguration(context));
    if (_imageStream!.key != oldImageStream?.key) {
      //如果键是相同的，那么我们得到相同的图像，所以我们不
      //需要更新侦听器。但是，如果密钥改变了，我们必须确保
      //将我们的侦听器切换到新的图像流。
      final ImageStreamListener listener = ImageStreamListener(_updateImage);
      oldImageStream?.removeListener(listener);
      _imageStream!.addListener(listener);
    }
  }

  void _updateImage(ImageInfo imageInfo, bool synchronousCall) {
    print("每当图像改变时触发构件");
    setState(() {
      //每当图像改变时触发构件。
      _imageInfo?.dispose();
      _imageInfo = imageInfo;
    });
  }

  @override
  void dispose() {
    _imageStream?.removeListener(ImageStreamListener(_updateImage));
    _imageInfo?.dispose();
    _imageInfo = null;
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return RawImage(
      image: _imageInfo?.image, // this is a dart:ui Image object
      scale: _imageInfo?.scale ?? 1.0,
    );
  }
}